#!/usr/bin/python3.2
#-*- coding: utf-8 -*-
import cherrypy
import couchdb
import os.path
import glob
import yaml
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('web'))

class dictToObject:
    def __init__(self, d):
        self.__dict__ = d
        
class Inventory:
    def __init__(self):
        self.db = couchdb.Server()['computers']
        
    @cherrypy.expose
    def default(self, group=None, computer=None):
        view = 'views/wszystkie'
        views = self.db['_design/views']['views']
        if group:
            if group in views:
                group = 'views/' + group
                if computer:
                    if self.db.view(group, None, key=computer).rows:
                        #Zwracam pełny rekord - z poza okrojonego widoku
                        computer = dictToObject(dict(self.db[computer]))
                        single = env.get_template('single.htm')
                        return single.render(machine=computer, categories=views.keys())
                    else:
                        raise cherrypy.HTTPError(404)
                else:
                    view = group
            else:
                raise cherrypy.HTTPError(404)
        
        list = env.get_template('index.htm')
        allhosts = [dictToObject(i['value']) for i in self.db.view(view)]
        return list.render(list=allhosts, categories=views.keys())
    
if __name__ == '__main__':
    currDir = os.path.dirname(os.path.abspath(__file__));
    config = yaml.load(open('config.yaml'))
    cherrypy.config.update(config['cherry'])
    
    cherrypy.engine.autoreload.files = set(glob.glob('web/*') + 
                                           glob.glob('*.py') +
                                           ['config.yaml']
                                       )
    cherrypy.engine.autoreload.subscribe()
    
    conf = {'/web': {'tools.staticdir.on': True,
                     'tools.staticdir.dir': os.path.join(currDir, 'web')}
            }
    
    cherrypy.quickstart(Inventory(), config=conf)
    
    